﻿package com.alstudio.utils.log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

import android.R.string;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

/**
 * Mylog类用于程序在运行期间的运行情况写到SD卡上以供开发人员查看。 本类提供
 * 
 * @author Alonso Lee
 * 
 */
public class LogUtil {

	private static File file = null;

	/* 以下为LOG级别 */
	public static final String INFO = "INFO"; // 普通信息
	public static final String WARN = "WARN"; // 警告
	public static final String ERROR = "ERROR"; // 错误

	public static String pathName = "";
	private static OutputStreamWriter outputStreamWriter;
	private static FileOutputStream stream = null;

	// 此常量为日志名
	public final static String fileName = "/AndroidRec.vmd";

	private static boolean isInit = false;
	private static boolean isFirstLog = true;

	// 此常量用于标识日志文件最大只能为1M
	private final static int MAX_FILE_SIZE = 1000 * 1000 * 2; // 1M

	private static boolean isLogEnable = true;

	private static Context mContext;

	public static void setLogEnable(boolean isLogEnable) {
		LogUtil.isLogEnable = isLogEnable;
	}

	public static void setLogFilePath(String path) {
		pathName = path;
	}

	private static BroadcastReceiver sdCardChange = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action != null) {
				if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
					File path = new File(pathName);
					file = new File(pathName + fileName);

					if (!path.exists()) {
						ALLog.d("Create the path:" + pathName);
						// 创建Log文件夹
						if (path.mkdirs() == false) {
							ALLog.d("mkdir error:" + pathName);
							return;
						}
					}
					if (!file.exists()) {
						ALLog.d("Create the file:" + fileName);
						try {
							if (file.createNewFile() == false) {
								ALLog.d("createNewFile error:" + fileName);
								return;
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						if (file.length() > MAX_FILE_SIZE) {
							file.delete();
							try {
								if (file.createNewFile() == false) {
									ALLog.d("createNewFile error:" + fileName);
									return;
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					}

					try {
						stream = new FileOutputStream(file, true);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
						outputStreamWriter = new OutputStreamWriter(stream,
								"GBK");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
					file = null;
					if (stream != null) {
						try {
							stream.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						stream = null;
					}
					if (outputStreamWriter != null) {
						try {
							outputStreamWriter.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						outputStreamWriter = null;
					}

				}
			}
		}
	};

	/**
	 * @param grade
	 *            本条消息的级别。取值范围为INFO、WARN、ERROR这三个常量
	 * @param tag
	 *            本消息所在文件名
	 * @param message
	 *            要输出的消息
	 */
	public static synchronized void logToSD(String grade, String tag,
			String message) {

		if (!isLogEnable) {
			return;
		}

		if (message == null) {
			return;
		}
		if (!isInit) {
			isInit = true;
			IntentFilter inf = new IntentFilter();
			inf.addAction(Intent.ACTION_MEDIA_MOUNTED);
			inf.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
			inf.addDataScheme("file");
			mContext.registerReceiver(sdCardChange, inf);

			if (file == null) {
				if (TextUtils.isEmpty(pathName))
					return;
				File path = new File(pathName);
				file = new File(pathName + fileName);

				if (!path.exists()) {
					// 创建Log文件夹
					if (path.mkdirs() == false) {
						return;
					}
				}
				if (!file.exists()) {
					try {
						if (file.createNewFile() == false) {
							return;
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				try {
					stream = new FileOutputStream(file, true);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					outputStreamWriter = new OutputStreamWriter(stream, "GBK");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		if (file != null) {
			if (file.exists()) {
				if (file.length() >= MAX_FILE_SIZE) {
					file.delete();
					createNewLogFile();
				}
			}
		}

		try {

			String curTime = new SimpleDateFormat("MM-dd HH:mm:ss")
					.format(System.currentTimeMillis());
			String messageBase = "";
			if (isFirstLog) {
				isFirstLog = false;
				messageBase += "\r\n/***********************************************************"
						+ curTime
						+ "开始更新日志"
						+ "***********************************************************************/\r\n";
				if (outputStreamWriter != null) {
					outputStreamWriter.write(messageBase);
					outputStreamWriter.flush();
				}
				messageBase = "";
			}

			// alonso 2011-8-17 取消输出tag信息
			messageBase = curTime + ": " + grade + "/" + message + "\r\n\r\n";

			if (outputStreamWriter != null) {
				outputStreamWriter.write(messageBase);
				outputStreamWriter.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建新的日志文件
	 * 
	 * @return true 创建成功；false 创建失败
	 */
	private static synchronized boolean createNewLogFile() {
		try {
			if (file.createNewFile() == false) {
				return false;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		try {
			stream = new FileOutputStream(file, true);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		try {
			outputStreamWriter = new OutputStreamWriter(stream, "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return true;
	}

}
